package com.copd.service.impl;

import com.copd.entity.Permission;
import com.copd.entity.Role;
import com.copd.mapper.PermissionMapper;
import com.copd.mapper.RoleMapper;
import com.copd.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.findAll();
    }
    
    @Override
    public Permission getPermissionById(Integer permissionId) {
        return permissionMapper.findById(permissionId);
    }
    
    @Override
    public Permission getPermissionByKey(String permissionKey) {
        return permissionMapper.findByPermissionKey(permissionKey);
    }
    
    @Override
    public Permission createPermission(Permission permission) {
        permissionMapper.insert(permission);
        return permission;
    }
    
    @Override
    public Permission updatePermission(Permission permission) {
        if (permissionMapper.update(permission) > 0) {
            return permission;
        }
        return null;
    }
    
    @Override
    public boolean deletePermission(Integer permissionId) {
        return permissionMapper.deleteById(permissionId) > 0;
    }
    
    @Override
    public List<Permission> getPermissionsByRoleId(Integer roleId) {
        return permissionMapper.findByRoleId(roleId);
    }
    
    @Override
    public List<Permission> getPermissionsByUserId(Integer userId) {
        // 获取用户所有的角色
        List<Role> roles = roleMapper.findByUserId(userId);
        
        // 使用Set避免权限重复
        Set<Permission> permissionSet = new HashSet<>();
        
        // 获取所有角色对应的权限
        for (Role role : roles) {
            List<Permission> permissions = permissionMapper.findByRoleId(role.getRoleId());
            permissionSet.addAll(permissions);
        }
        
        return new ArrayList<>(permissionSet);
    }
    
    @Override
    public boolean updateUserPermissions(Integer userId, List<String> permissionKeys) {
        try {
            // 首先获取所有权限键对应的权限ID
            List<Integer> permissionIds = new ArrayList<>();
            for (String key : permissionKeys) {
                Permission permission = permissionMapper.findByPermissionKey(key);
                if (permission != null) {
                    permissionIds.add(permission.getPermissionId());
                }
            }
            
            // 创建特定用户角色，名称为"user_特定ID"
            String customRoleName = "user_" + userId;
            String customRoleKey = "user_role_" + userId; // 添加唯一的role_key值
            
            Role customRole = roleMapper.findByName(customRoleName);
            
            // 如果自定义角色不存在，则创建一个
            if (customRole == null) {
                customRole = new Role();
                customRole.setRoleName(customRoleName);
                customRole.setRoleKey(customRoleKey); // 设置role_key字段
                customRole.setDescription("用户 " + userId + " 的自定义权限角色");
                roleMapper.insert(customRole);
            }
            
            // 清除该角色的所有现有权限
            roleMapper.deleteRolePermissions(customRole.getRoleId());
            
            // 为该角色设置新的权限
            if (!permissionIds.isEmpty()) {
                roleMapper.insertRolePermissions(customRole.getRoleId(), permissionIds);
            }
            
            // 确保用户拥有此角色
            // 先检查用户是否已有此角色
            boolean hasRole = roleMapper.checkUserHasRole(userId, customRole.getRoleId());
            if (!hasRole) {
                roleMapper.assignRoleToUser(userId, customRole.getRoleId());
            }
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
} 